package com.alks.function.controller.biocontrol.webWork;

import com.alks.common.aop.ApiRestController;
import com.alks.common.aop.WebLogger;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.biocontrol.webwork.ProdOutTempDto;
import com.alks.function.data.request.biocontrol.webwork.ProdOutRequest;
import com.alks.function.service.biocontrol.deptwork.IProdOutService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * @author MS
 * @since 2024/12/4下午2:20
 */
@RestController
@ApiRestController("/ProdOut")
@Api(value = "生控部", tags = "生控部-web页面-出货明细")
@Slf4j
public class ProdOutController {
    @Autowired
    private IProdOutService service;

    @WebLogger
    @PostMapping("/temp/query")
    @ApiOperation(value = "明细查询", tags = "生控部-web页面-出货明细")
    public ResponseInfo tempQuery(@RequestBody ProdOutRequest request) {
        return ResponseInfo.ok(service.tempQuery(request));
    }

    @WebLogger
    @GetMapping("/temp/back")
    @ApiOperation(value = "回显", tags = "生控部-web页面-出货明细")
    public ResponseInfo back(@RequestParam(required = false) String vendorSearch,
                             @RequestParam(required = false) String brandSearch) {
        return ResponseInfo.ok(service.back(vendorSearch,brandSearch));
    }

    @WebLogger
    @PostMapping("/temp/export")
    @ApiOperation(value = "导出", tags = "生控部-web页面-出货明细")
    public void tempExport(@RequestBody ProdOutRequest request, HttpServletResponse response) {
        request.setPageSize(-1);
        PageRecord<ProdOutTempDto> record = service.tempQuery(request);
        List<ProdOutTempDto> dtoList =record.getList();
        if (ArrayUtils.isEmpyt(dtoList)){
            throw new ServiceErrorException("暂无可导出数据");
        }
        Map<String, Object> other = record.getOther();
        String templateName = "出货明细模版.xls";
        String excelName = "出货明细_"+ LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+".xls";
        try {
            ExcelUtils.autoWidth().creatByTemplate(response, templateName,excelName,dtoList,other);
        } catch (IOException e) {
            log.error("导出失败：\n",e);
            throw new ServiceErrorException("导出失败");
        }
    }

}